package cn.icanci.loopstack.rec.admin.web.controller.config;

import cn.icanci.loopstack.rec.admin.biz.model.BaseDataDebugResult;
import cn.icanci.loopstack.rec.admin.biz.service.BaseDataService;
import cn.icanci.loopstack.rec.admin.web.mapper.BaseDataWebMapper;
import cn.icanci.loopstack.rec.admin.web.form.BaseDataDebugForm;
import cn.icanci.loopstack.rec.admin.web.form.BaseDataQueryForm;
import cn.icanci.loopstack.rec.admin.web.model.BaseData;
import cn.icanci.loopstack.rec.common.model.TextValue;
import cn.icanci.loopstack.rec.common.model.config.BaseDataVO;
import cn.icanci.loopstack.rec.common.result.R;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.*;

/**
 * @author icanci
 * @since 1.0 Created in 2022/11/12 20:30
 */
@RestController
@RequestMapping("/rec/baseData")
public class BaseDataController {
    @Resource
    private BaseDataService   baseDataService;
    @Resource
    private BaseDataWebMapper baseDataWebMapper;

    // ================================ CRUD ================================
    @PostMapping("query")
    public R query(@RequestBody BaseDataQueryForm form) {
        return R.builderOk()
            .data("queryPage", baseDataService.queryPage(baseDataWebMapper.web2vo(form.getBaseData()), form.getPaginator().getCurrentPage(), form.getPaginator().getPageSize()))
            .build();
    }

    @PostMapping("save")
    public R save(@RequestBody BaseData baseData) {
        baseDataService.save(baseDataWebMapper.web2vo(baseData));
        return R.builderOk().build();
    }

    @GetMapping("validateFieldName/{fieldName}/{domainCode}")
    public R validateFieldName(@PathVariable("fieldName") String fieldName, @PathVariable("domainCode") String domainCode) {
        BaseDataVO baseData = baseDataService.queryByFieldNameAndDomainCode(fieldName, domainCode);
        return R.builderOk().data("result", baseData == null).build();
    }
    // ================================ Load Selectors ================================

    @GetMapping("loadSelector/{domainCode}")
    public R loadSelector(@PathVariable("domainCode") String domainCode) {
        List<TextValue> textValues = baseDataService.loadSelector(domainCode);
        return R.builderOk().data("textValues", textValues).build();
    }
    // ================================ Debug ================================

    @PostMapping("debug")
    public R debug(@RequestBody BaseDataDebugForm form) {
        BaseDataDebugResult result = baseDataService.debug(baseDataWebMapper.web2vo(form.getBaseData()), form.getScriptContentTest());
        return R.builderOk().data("result", result).build();
    }

    @GetMapping("baseDataQueryByUuid/{uuid}")
    public R baseDataQueryByUuid(@PathVariable("uuid") String uuid) {
        BaseDataVO result = baseDataService.baseDataQueryByUuid(uuid);
        return R.builderOk().data("result", baseDataWebMapper.vo2web(result)).build();
    }
}
